package busca.tesoros.uclm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MostrarQRActivity extends Activity {
	

	public static final String SERVERIP = "192.168.1.6";
	public static final int SERVERPORT = 8080;

	private static final int ACTIVITY_RESULT_QR_DRDROID = 0;
	private boolean image = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.qrusuario);
		  String response="";
		try {
			Log.i("Client", "Conectting to "+ SERVERIP + ":" + SERVERPORT);
			InetAddress serverAddr = InetAddress.getByName(SERVERIP);
			Socket clientSocket = new Socket(serverAddr, SERVERPORT);
			 String inTxt = "";
			  
			if(clientSocket.isConnected()) {
				
				PrintWriter out = new PrintWriter(
					new BufferedWriter(new OutputStreamWriter(clientSocket
						.getOutputStream())), true);

				out.println("{ operacion:'imagenQR' }");

				BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()),1024);

				        			
				Log.i("Client", "Response from server:\n");
				String line;
				
				while ((line = in.readLine()) != null) {
					Log.i("Client", line);
					inTxt += line;
				}
				
				JSONObject inJson = new JSONObject(inTxt);
				response= inJson.getString("response");
				Log.i("Client", "-----------------\n");
			}
			clientSocket.close();
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		
		
		//Create a new Intent to send to QR Droid
		Intent qrDroid = new Intent( "la.droid.qr.encode"); //Set action "la.droid.qr.encode"
		
		//Set text to encode
		qrDroid.putExtra("la.droid.qr.code", "Detectives UCLM\nCode:PR-"+response+"\nVersion: 1");

		((TextView)findViewById(R.id.user)).setText("Usuario: "+response);
			image = true;
			qrDroid.putExtra( "la.droid.qr.image"  , true);
			//Optionally, set requested image size. 0 means "Fit Screen"
			qrDroid.putExtra( "la.droid.qr.size"  , 0 );
		
		
		//Send intent and wait result
		
			try {
				startActivityForResult(qrDroid, ACTIVITY_RESULT_QR_DRDROID);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		
	}
	
	@Override
	/**
	 * Reads generated QR code
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if( ACTIVITY_RESULT_QR_DRDROID==requestCode && null!=data && data.getExtras()!=null ) {
			//Read result from QR Droid (it's stored in la.droid.qr.result)
			//Result is a string or a bitmap, according what was requested
			ImageView imgResult = ( ImageView ) findViewById(R.id.img_result);
			EditText txtResult = ( EditText ) findViewById(R.id.txt_result);
			
			if( image ) {
				String qrCode = data.getExtras().getString( "la.droid.qr.result");
				
				//If image path was not returned, it could not be saved. Check SD card is mounted and is writable
				if( null==qrCode || 0==qrCode.trim().length() ) {
					Toast.makeText( MostrarQRActivity.this , R.string.not_saved, Toast.LENGTH_LONG).show();
					return;
				}
				
				
				//Load QR code image from given path
				imgResult.setImageURI( Uri.parse(qrCode) );
				
				imgResult.setVisibility( View.VISIBLE );
				txtResult.setVisibility( View.GONE );
				
				//TODO: After using this QR code, you should move it to a permanent location, or delete it
			} else {
				String result = data.getExtras().getString("la.droid.qr.result");
				//Just set result to EditText to be able to view it
				txtResult.setText( result );
				txtResult.setVisibility( View.VISIBLE );
				imgResult.setVisibility( View.GONE );
			}
		}
	}
	
	@Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	//Nothing
    }
	
	
	//
	//   Control Menu
	//
	private static final int MNU_OPC1 = 1;
	private static final int MNU_OPC2 = 2;
	private static final int MNU_OPC3 = 3;
	
	private static final int SMNU_OPC1 = 31;
	private static final int SMNU_OPC2 = 32;
	Boolean star=false;
	private TextView lblMensaje;
	MediaPlayer mp;
				
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	Intent qr;
    	
        switch (item.getItemId()) {
        
            case R.id.menuimagen:
            	qr = new Intent(this,MostrarQRActivity.class);
          		startActivity(qr);		             
          		 return true;
          		               
            case R.id.menusalir:
            	qr = new Intent(this, FinActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            	startActivity(qr);
            	finish();
            	 return true;
            	 
            case R.id.menusonido:
            	if(star)
            	{
            	mp.stop();
            	star=false;
            	}
            	else
            	{		            		
                    mp = MediaPlayer.create(this, R.raw.melodia_de_fondo);
	            	mp.setLooping(true);
            		mp.start();
            		star=true;
            	}
            	return true;
		default:
                return super.onOptionsItemSelected(item);
        }
    }
}
